package com.venutech.gongan.service.impl;

import com.baomidou.mybatisplus.plugins.Page;
import com.venutech.gongan.common.Constants;
import com.venutech.gongan.common.InternalUserType;
import com.venutech.gongan.dao.PrivilegeMapper;
import com.venutech.gongan.dao.RolePrivilegeMapper;
import com.venutech.gongan.dao.SpGrantMapper;
import com.venutech.gongan.dao.UserMapper;
import com.venutech.gongan.entity.Privilege;
import com.venutech.gongan.entity.User;
import com.venutech.gongan.model.ResultFormat;
import com.venutech.gongan.service.UserGroupRoleService;
import com.venutech.gongan.service.UserService;
import com.venutech.gongan.util.ResultUtil;
import com.venutech.gongan.vo.UserDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;


@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UserMapper userMapper;

    @Autowired
    private PrivilegeMapper privilegeMapper;

    @Autowired
    private RolePrivilegeMapper rolePrivilegeMapper;

    @Autowired
    PasswordEncoder passwordEncoder;

    @Autowired
    SpGrantMapper spGrantMapper;

    @Autowired
    UserGroupRoleService userGroupRoleService;

    @Override
    public ResultFormat insert(User user) {
        //查询用户是否存在
        User u = userMapper.searchUserName(user.getLogin_user_name());
        if (u!=null){
            return ResultUtil.error(101, "用户名已存在");
        }
        Integer insert = userMapper.insert(user);
        if (insert > 0) {
            return ResultUtil.success();
        }else {
            return ResultUtil.error(100,"用户添加失败");
        }

    }

    @Override
    public User searchUserName(String login_user_name) {
        return userMapper.searchUserName(login_user_name);
    }

    @Override
    public User login(String login_user_name, String login_password) {
        return userMapper.login(login_user_name,login_password);
    }

    @Override
    public List<User> selectAll() {
        return userMapper.selectAll();
    }

    @Override
    public int deleteById(Integer user_id) {
        return userMapper.deleteById(user_id);
    }

    @Override
    public User getById(Integer user_id) {
        return userMapper.getById(user_id);
    }

    @Override
    public int updateUser(User user) {
        return userMapper.updateUser(user);
    }

    //分页查询
    @Override
    public Page<User> getInfo(Integer pageNo, Integer pageSize, String begintime, String endtime, String badw, String login_user_name) {
        Page<User> page = new Page<>(pageNo,pageSize);
        List<User> list = userMapper.getInfo(begintime,endtime,badw,page,login_user_name);
        return page.setRecords(list);
    }

    //用户组添加用户分页查询
    @Override
    public Page<User> getInfoEmpno(Integer pageNo, Integer pageSize, String employee_no) {
        Page<User> page = new Page<>(pageNo,pageSize);
        List<User> list = userMapper.getInfoEmpno(page,employee_no);
        return page.setRecords(list);
    }

//    /**
//     * 继承自spring-security的UserDetailsService，OAuth2获取用户信息
//     * 此处username传警号employeeNo
//     * @param username
//     * @return
//     * @throws UsernameNotFoundException
//     */
//    @Override
//    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//        //String md5pwd = MD5Util.MD5Encode("111111", "UTF-8");
//
//        User user = userMapper.getByEmployeeNo(username);
//
//        // 角色、权限
//        List<GrantedAuthority> authorities = new ArrayList<>();
//
//        if(user.getUser_type() == InternalUserType.RESERVED_USER.getValue()) {  // 保留用户直接拥有管理员权限
//            authorities.add(new SimpleGrantedAuthority("ROLE_"+ Constants.RESERVED_ROLE_NAME_ADMIN));
//        }
//
//        return new org.springframework.security.core.userdetails.User(username, passwordEncoder.encode(user.getLogin_password()), authorities);
//
//    }



    //    public boolean verifyCredential(String username, String password) {
//        return true;
//    }

    public User findUserByEmployeeNo(String employeeNo) {
        User user = userMapper.getByEmployeeNo(employeeNo);
        return user;
    }

    public UserDto getUserById(int userId) {
        User user = userMapper.getById(userId);
        return assembleUserDto(user);
    }

    public UserDto getUserByEmployeeNo(String employeeNo) {
        User user = userMapper.getByEmployeeNo(employeeNo);
        return assembleUserDto(user);
    }

    @Override
    public List<Integer> getUserRoles(Integer userId) {
        List<Integer> roleIds = userMapper.getUserRoles(userId);
        return roleIds;
    }

    @Override
    public boolean checkAdmin(Integer userId) {
        User user = getById(userId);
        if(Objects.isNull(user)) {
            return false;
        }

        return user.getUser_type() == InternalUserType.ADMIN_USER.getValue() || user.getUser_type() == InternalUserType.RESERVED_USER.getValue();
    }

    /**
     * 根据用户Id和当前访问页面的code查询按钮资源的权限列表
     * @param userId
     * @param privilegeCode
     * @return
     */
    @Override
    public List<String> getUserButtonPrivilegeList(Integer userId, String privilegeCode) {
        List<String> privilegeCodes = new ArrayList<>();
        if(checkAdmin(userId)) {
            privilegeCodes.add("ALL");
            return privilegeCodes;
        }

        List<Integer> roleIds = getUserAllRoleIds(userId);
        if(CollectionUtils.isEmpty(roleIds)) {
            return privilegeCodes;
        }

        List<Privilege> buttonPrivileges = privilegeMapper.getByCode(privilegeCode);
        if(CollectionUtils.isEmpty(buttonPrivileges)) {
            return privilegeCodes;
        }

        List<Integer> allUserButtonPrivilegeIds = rolePrivilegeMapper.getPrivilegeIdsByRoleIds(roleIds);
        if(CollectionUtils.isEmpty(allUserButtonPrivilegeIds)) {
            return privilegeCodes;
        }

        List<Privilege> userButtonPrivileges = buttonPrivileges.stream().filter(p -> allUserButtonPrivilegeIds.contains(p.getPrivilege_id())).collect(Collectors.toList());
        if(CollectionUtils.isEmpty(userButtonPrivileges)) {
            return privilegeCodes;
        }

        privilegeCodes = userButtonPrivileges.stream().map(p -> p.getPrivilege_code()).collect(Collectors.toList());
        return privilegeCodes;
    }

    /**
     * 根据用户Id查询菜单资源的权限列表
     * @param userId
     * @return
     */
    @Override
    public List<String> getUserMenuPrivilegeList(Integer userId) {
        List<String> privilegeCodes = new ArrayList<>();
        if(checkAdmin(userId)) {
            privilegeCodes.add("ALL");
            return privilegeCodes;
        }

        List<Integer> roleIds = getUserAllRoleIds(userId);
        if(CollectionUtils.isEmpty(roleIds)) {
            return privilegeCodes;
        }

        List<Privilege> menuPrivileges = privilegeMapper.getByType(Constants.PRIVILEGE_TYPE_MENU);
        if(CollectionUtils.isEmpty(menuPrivileges)) {
            return privilegeCodes;
        }

        List<Integer> allUserMenuPrivilegeIds = rolePrivilegeMapper.getPrivilegeIdsByRoleIds(roleIds);
        if(CollectionUtils.isEmpty(allUserMenuPrivilegeIds)) {
            return privilegeCodes;
        }

        List<Privilege> userMenuPrivileges = menuPrivileges.stream().filter(p -> allUserMenuPrivilegeIds.contains(p.getPrivilege_id())).collect(Collectors.toList());
        if(CollectionUtils.isEmpty(userMenuPrivileges)) {
            return privilegeCodes;
        }

        privilegeCodes = userMenuPrivileges.stream().map(p -> p.getPrivilege_code()).collect(Collectors.toList());
        return privilegeCodes;
    }

    @Override
    public List<Integer> getUserAllRoleIds(Integer userId) {
        List<Integer> roleIds = new ArrayList<>();
        List<Integer> userRoleIds = getUserRoles(userId);
        if(!CollectionUtils.isEmpty(userRoleIds)) {
            roleIds.addAll(userRoleIds);
        }
        List<Integer> usergroupRoleIds = userGroupRoleService.getUserGroupRoles(userId);
        if(!CollectionUtils.isEmpty(usergroupRoleIds)) {
            if(CollectionUtils.isEmpty(roleIds)) {
                roleIds.addAll(usergroupRoleIds);
            } else {
                List<Integer> newRoleIds = new ArrayList<>();
                for(Integer roleId :usergroupRoleIds) {
                    if(!roleIds.contains(roleId)) {
                        newRoleIds.add(roleId);
                    }
                }
                roleIds.addAll(newRoleIds);
            }
        }
        return roleIds;
    }

//    /**
//     * 查询用户临时视频权限表
//     * @param userId
//     * @param poleId
//     * @param equipId
//     * @return
//     */
//    @Override
//    public List<SpGrant> getVideoPrivileges(int userId, int poleId, int equipId) {
//
//        List<SpGrant> spGrantList = spGrantMapper.getByPoldIdAndEquipId(userId, poleId, equipId);
//        return spGrantList;
//    }

    @Override
    public int updateUserPassword(int userId, String newPassword) {
        return userMapper.updateUserPassword(userId, newPassword);
    }

    @Override
    public UserDto assembleUserDto(User user) {
        if(Objects.isNull(user)) {
            return null;
        }

        UserDto userDto = new UserDto();
        userDto.setUserId(user.getUser_id());
        userDto.setUserName(user.getLogin_user_name());
        userDto.setUserType(user.getUser_type());
        userDto.setNickName(user.getNick_name());
        userDto.setEmployeeNo(user.getEmployee_no());
        userDto.setImageName(user.getImage_name());
        userDto.setLocked(user.getLocked());
        userDto.setCreateBy(user.getCreate_by());
        userDto.setCreateTime(user.getCreate_time());
        userDto.setUpdateBy(user.getUpdate_by());
        userDto.setUpdateTime(user.getUpdate_time());
        userDto.setAreaCode(user.getUser_area());

        return userDto;
    }


}
